package com.luyuan.yuansousuo.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luyuan.yuansousuo.common.ErrorCode;
import com.luyuan.yuansousuo.exception.BusinessException;
import com.luyuan.yuansousuo.model.entity.Picture;
import com.luyuan.yuansousuo.service.PictureService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
@Slf4j
public class PictureServiceImpl implements PictureService {
    @Override
    public Page<Picture> searchPicture(String searchText, long pageNum, long pageSize) {
        // 计算当前的页数
        long current = (pageNum - 1) * pageSize;
        // 获取资源的url
        String url = String.format("https://cn.bing.com/images/search?q=%s&first=%d", searchText, current);
        Document document = null;
        try {
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据获取异常");
        }
        // 找到 CSS 父类 id
        Elements elements = document.select(".iuscp.isv");
        // 存放获取到的图片地址
        ArrayList<Picture> pictures = new ArrayList<>();
        for (Element element : elements) {
            // 1. 获取图片地址
            String m = element.select(".iusc").get(0).attr("m");
            // m 这个 json对象
            Map<String, Object> map = JSONUtil.toBean(m, Map.class);
            String murl =  (String) map.get("murl");
            // 2. 获取标题
            String title = element.select(".inflnk").get(0).attr("aria-label");
            // 3. 封装每个图片的地址和标题
            Picture picture = new Picture();
            picture.setTitle(title);
            picture.setUrl(murl);
            pictures.add(picture);
            // 控制每页在 pageSize 之内
            if (pictures.size() >= pageSize) {
                break;
            }
        }
        // 将 pictures 封装到分页对象中 便于返回
        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        picturePage.setRecords(pictures);
        return picturePage;
    }
}
